import * as crypto from "crypto";
import * as qs from "qs";
// import CryptoJS from 'crypto-js'

const errorMsgType: Record<number, string> = {
  105: "密码错误",
  302: "接口重定向了！",
  400: "参数不正确",
  401: "您未登录，或者登录已经超时，请先登录！",
  403: "您没有权限操作",
  404: "请求地址出错: ",
  408: "请求超时",
  409: "系统已存在相同数据",
  500: "服务器内部错误",
  501: "服务未实现",
  502: "网关错误",
  503: "服务不可用",
  504: "服务暂时无法访问，请稍后再试",
  505: "HTTP版本不受支持",
  601: "房间不存在",
};

export default errorMsgType;

export function getWebSocketUrl(room_id: number) {
  return encrypt(`timeStamp=${getTimeStamp()}&room_id=${room_id}`);
}

export function success(msg = "success", data = null): responseType {
  return {
    code: 200,
    msg,
    data,
  };
}

export function error(msg: string, code = 500): responseType {
  return {
    code,
    msg,
  };
}

export function decrypt(value: string, keygen = "2cef781a9c0411eb") {
  const key = Buffer.from(keygen, "utf8");
  const iv = Buffer.alloc(16, 0);
  try {
    const decipher = crypto.createDecipheriv("aes-128-cbc", key, iv);
    let decrypted = decipher.update(value, "base64", "utf-8");
    decrypted += decipher.final();
    return decrypted;
  } catch (error) {
    return "";
  }
}

export function encrypt(value: string, keygen = "2cef781a9c0411eb") {
  const key = Buffer.from(keygen, "utf8");
  const iv = Buffer.alloc(16, 0);
  const cipher = crypto.createCipheriv("aes-128-cbc", key, iv);
  let encrypted = cipher.update(value, "utf8", "base64");
  encrypted += cipher.final("base64");
  return encrypted;
}

export function getTimeStamp(): number {
  return Math.floor(Date.now() / 1000);
}

export function queryString<T = any>(url: string) {
  return qs.parse(url);
}

/**
 *
 * @param range 范围
 * @returns 返回一个整数，但是不包括range自身
 */
export function getRandomInt(range: number): number {
  return Math.floor(Math.random() * range);
}

export async function validateRequest(values: any) {
  values.token;
}

/**
 * 生成a-b的范围的随机整数
 * @param a number
 * @param b number
 */
export function randomRangeInt(a: number, b: number) {
  let max: number, min: number;
  if (a > b) {
    max = a;
    min = b;
  } else {
    max = b;
    min = a;
  }
  const num = Math.floor(Math.random() * (max - min + 1)) + min;
  return num;
}

export function getAuth() {
  const temp = crypto
    .createHash("sha1")
    .update(`${getTimeStamp()}`)
    .digest("hex");
  return crypto
    .createHash("sha1")
    .update(`${temp}${getRandomInt(3000)}${getRandomInt(2000)}`)
    .digest("hex");
}

export function checkMimeType() {}
